<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\WanlSdk\Common;
use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use fast\Tree;
use think\Db;
use think\Log;


class Home extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @param mixed $arg1
     * @author xusir
     * @date: 2023/5/15
     * @createTime: 16:59
     * @remark:商品推荐列表
     */
    public function tjList()
    {
        $redis = Common::redis();
        $page = $this->request->get('page', 1);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        // 判断业务类型
        $goodsModel = model('app\api\model\wanlshop\Goods');
        // 生成搜索条件
        list($where, $sort, $order) = $this->buildparams('title,category.name', false); // 查询标题 和类目字段  ！！！！！！排除已下架//-------------------------------------------

        $key = 'tjList_' . $page . '_' . md5(json_encode($where) . $sort . $order);
        if ($redis->exists($key)) {
            $value = $redis->get($key);
            $list = json_decode($value, 256);
        } else {
            // 查询数据
            $list = $goodsModel
                /*->with([
                    'shop_goods' => function ($query) {
                        $query->withField(['id', 'city', 'shopname', 'state', 'isself']);
                    },
                    'category' => function ($query) {
                        $query->withField(['id', 'pid', 'name']);
                    }
                ])*/
                ->where($where)
                ->where('status', 'normal')
                ->where('is_tj', '1')
                ->field('content', true)
                ->order('price', 'asc')
                ->paginate();
            /*foreach ($list as $row) {
                $row->getRelation('shop_goods')->visible(['city', 'shopname', 'state', 'isself']);
                $row->getRelation('category')->visible(['id','pid','name']);
                $row->isLive = model('app\api\model\wanlshop\Live')->where(['shop_id' => $row['shop_id'], 'state' => 1])->field('id')->find();
            }*/
            $redis->set($key, json_encode($list));
            $redis->expire($key, 3600);
        }
        $this->success('返回成功', $list);
    }

    /**
     * @param mixed $arg1
     * @author xusir
     * @date: 2023/5/16
     * @createTime: 11:43
     * @remark:商品最新上架
     */
    public function newList()
    {
        $redis = Common::redis();
        $page = $this->request->get('page', 1);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        // 判断业务类型
        $goodsModel = model('app\api\model\wanlshop\Goods');
        // 生成搜索条件
        list($where, $sort, $order) = $this->buildparams('title,category.name', false); // 查询标题 和类目字段  ！！！！！！排除已下架//-------------------------------------------

        $key = 'newList_' . $page . '_' . md5(json_encode($where) . $sort . $order);
        if ($redis->exists($key)) {
            $value = $redis->get($key);
            $list = json_decode($value, 256);
        } else {
            // 查询数据
            $list = $goodsModel
//            ->with(['shop_goods', 'category'])
                ->where($where)
                ->where('status', 'normal')
                ->where('is_new', '1')
                ->field('content', true)
                ->order('price', 'asc')
                ->paginate();
            /*foreach ($list as $row) {
                $row->getRelation('shop_goods')->visible(['city', 'shopname', 'state', 'isself']);
                $row->getRelation('category')->visible(['id', 'pid', 'name']);
                $row->isLive = model('app\api\model\wanlshop\Live')->where(['shop_id' => $row['shop_id'], 'state' => 1])->field('id')->find();
            }*/
            $redis->set($key, json_encode($list));
            $redis->expire($key, 3600);
        }
        $this->success('返回成功', $list);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        // 获取传参
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $name = $this->model->getTable();
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }


        // 判断是否需要验证权限
        // if (!$this->auth->match($this->noNeedLogin)) {
        //     $where[] = [$tableName . 'user_id', 'in', $this->auth->id];
        // }

        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $arrSearch = [];
            foreach (explode(" ", $search) as $ko) {
                $arrSearch[] = '%' . $ko . '%';
            }
            $where[] = [implode("|", $searcharr), "LIKE", $arrSearch];
        }
        // 历遍所有
        if (array_key_exists('category_id', $filter)) {
            $filter['category_id'] = implode(',', array_column(Tree::instance()->init(model('app\api\model\wanlshop\Category')->all())->getChildren($filter['category_id'], true), 'id'));
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order];
    }


    /**
     * @param mixed $arg1
     * @author xusir
     * @date: 2023/5/16
     * @createTime: 13:44
     * @remark:获取分类
     */
    public function getCategory()
    {
        $cacheTime = 60;
        // 类目
        $tree = Tree::instance();
        $tree->init(model('app\api\model\wanlshop\Category')
            ->where(['type' => 'goods', 'isnav' => 1])
            ->cache(true, $cacheTime)
            ->field('id, pid, name, image')
            ->order('weigh asc')
            ->select());
        $list = $tree->getTreeArray(0);
        $this->success('返回成功', $list);
    }


    /**
     * @param mixed $arg1
     * @author xusir
     * @date: 2023/6/14
     * @createTime: 14:08
     * @remark:检查购物车进行提醒
     */
    public function checkCart()
    {
        $config = get_addon_config('wanlshop');

        echo "<pre>";
        var_dump($config['config']['warn_time']);
        exit;
    }


}
